<?php

namespace App\Service\WorkOrder\Mission;


use App\Enums\BaseErrorCode;
use App\Enums\WorkOrder\OrderEnum;
use App\Exceptions\Custom\ResponseHttpException;
use App\Http\Middleware\OpenShop\FeishuWebAuth;
use App\Http\Middleware\OpenShop\UserPermissionAuth;
use App\Models\WorkOrder\WorkOrderApplyMainModel;
use App\Models\WorkOrder\WorkOrderApplyManagerModel;
use App\Service\BaseService;
use App\Service\WorkOrder\Message\SendFsService;
use App\Support\FeishuMsgSupport;
use Exception;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Support\Facades\Cache;

class MissionNoticeService extends BaseService
{

    /**
     * @param string $workOrderNo
     * @param int $step
     * @return string
     */
    public static function getMerchantNoticeCacheKey(string $workOrderNo, int $step): string
    {
        return vsprintf(
            "workOrder:merchant:pressNotice:%s:%s", [
            $workOrderNo,
            $step
        ]);
    }

    /**
     * @param string $workOrderNo
     * @param int $step
     * @param int $initiator
     * @param int $receiver
     * @return string
     */
    public static function getWebNoticeCacheKey(string $workOrderNo, int $step, int $initiator, int $receiver): string
    {
        return vsprintf(
            "workOrder:web:pressNotice:%s:%s:%s:%s", [
            $workOrderNo,
            $step,
            $initiator,
            $receiver
        ]);
    }

    /**
     * @param string $workOrderNo
     * @throws GuzzleException
     * @throws Exception
     */
    public static function pressNotice(string $workOrderNo)
    {
        try {
            $applyMain = WorkOrderApplyMainModel::getApplyStayMissionByWorkOrderNo($workOrderNo);

            self::canPressNoticed($applyMain, true);

            // 飞书消息 - 催办
            (new SendFsService($workOrderNo))->cuiBan($applyMain->missionsRel->pluck("dealUid")->toArray());

            Cache::put(
                self::getMerchantNoticeCacheKey($workOrderNo, $applyMain->step),
                true,
                strtotime(formatDateYmd(strtotime("+1 day"))) - time()
            );
        } catch (Exception $exception) {
            handleException($exception);
        }
    }

    /**
     * @param WorkOrderApplyMainModel $applyMainModel
     * @param bool $throwException
     * @return bool
     */
    public static function canPressNoticed(WorkOrderApplyMainModel $applyMainModel, bool $throwException = false): bool
    {
        if (date("Y-m-d", time()) == formatDateYmd($applyMainModel->createdAt->timestamp)) {
            if($throwException){
                throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "当天发起的工单不支持催单操作");
            }
            return false;
        }

        if (Cache::has(self::getMerchantNoticeCacheKey($applyMainModel->workOrderNo, $applyMainModel->step))) {
            if($throwException){
                throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "已达当天催单次数上限");
            }
            return false;
        }

        return true;
    }

    public static function isWebPressNoticedToday(string $workOrderNo, int $step, int $initUid, int $receiverUid): bool
    {
        if (Cache::has(self::getWebNoticeCacheKey($workOrderNo, $step, $initUid, $receiverUid))) {
            return true;
        }
        return false;
    }

    /**
     * @param int $id
     * @param string $workOrderNo
     * @throws GuzzleException
     */
    public static function missionNotice(int $id, string $workOrderNo)
    {
        try {
            $initUid     = FeishuWebAuth::$userId;
            $applyMain   = WorkOrderApplyMainModel::getApplyStayMissionByWorkOrderNo($workOrderNo);
            $managerInfo = WorkOrderApplyManagerModel::query()->where("id", $id)->first();
            $username    = request()->user()->username;

            if (date("Y-m-d", time()) == formatDateYmd($applyMain->createdAt->timestamp)) {
                throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "当天发起的工单不支持催单操作");
            }

            if (self::isWebPressNoticedToday($workOrderNo, $applyMain->step, $initUid, $managerInfo->managerId)) {
                throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "已达当天催单次数上限");
            }

            // 飞书消息 - 催办
            (new SendFsService($workOrderNo))->cuiBan([$managerInfo->managerId], $username);

            Cache::put(
                self::getWebNoticeCacheKey($workOrderNo, $applyMain->step, $initUid, $managerInfo->managerId),
                true,
                strtotime(formatDateYmd(strtotime("+1 day"))) - time()
            );

        } catch (Exception $exception) {
            handleException($exception);
        }
    }

}
